package com.changgou.goods.service.impl;

import com.changgou.goods.dao.SkuMapper;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.service.SkuService;
import com.changgou.orders.pojo.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SkuServiceImpl implements SkuService {
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map search(Map<String, String> searchMap) {
        String keywords=searchMap.get("keywords");
        if(StringUtils.isEmpty(keywords)){
            keywords="TCL";
        }
        List<Sku> skuList=skuMapper.searchByName("%"+keywords+"%");
        Map resultMap=new HashMap();
        resultMap.put("rows",skuList);
        return resultMap;
    }

    @Override
    public List<Sku> findList(Sku sku) {
        return skuMapper.select(sku);
    }
    /***
     * 库存递减
     * @param username
     */
    @Override
    public void decrCount(String username) {
        //获取购物车数据
        List<OrderItem> orderItems = redisTemplate.boundHashOps("Cart_" + username).values();

        //循环递减
        for (OrderItem orderItem : orderItems) {
            //递减库存
            int count = skuMapper.decrCount(orderItem);
            if(count<=0){
                throw new RuntimeException("库存不足，递减失败！");
            }
        }
    }
}